<?php

namespace App\Service\System;

/**
 * 加解密通用
 */
class EncryptionService
{
    /**
     * rsa加密
     * @param $data
     * @param $publicKey
     * @return string
     */
    public function rsaEncrypt($data, $publicKey) {
        openssl_public_encrypt($data, $encryptedData, $publicKey);
        return base64_encode($encryptedData);
    }

    /**
     * rsa解密
     * @param $encryptedData
     * @param $privateKey
     * @return mixed
     */
    public function rsaDecrypt($encryptedData, $privateKey) {
        $encryptedData = base64_decode($encryptedData);
        openssl_private_decrypt($encryptedData, $decryptedData, $privateKey);
        return $decryptedData;
    }

    function aesCbcEncrypt($data, $key, $iv = '') {
        $algo = match (strlen($key)) {
            24 => 'AES-192-CBC',
            32 => 'AES-256-CBC',
            default => 'AES-128-CBC',
        };
        if(empty($iv)){
            $encryptedData = openssl_encrypt($data, $algo, $key);
        }else{
            $encryptedData = openssl_encrypt($data, $algo, $key, 0, $iv);
        }

        return base64_encode($encryptedData);
    }

    function aesCbcDecrypt($encryptedData, $key, $iv = '') {
        $algo = match (strlen($key)) {
            24 => 'AES-192-CBC',
            32 => 'AES-256-CBC',
            default => 'AES-128-CBC',
        };
        $encryptedData = base64_decode($encryptedData);
        if(empty($iv)){
            $decryptedData = openssl_decrypt($encryptedData, $algo, $key);
        }else{
            $decryptedData = openssl_decrypt($encryptedData, $algo, $key, 0, $iv);
        }
        return $decryptedData;
    }


    function aesEcbEncrypt($data, $key, $iv = '') {
        $algo = match (strlen($key)) {
            24 => 'AES-192-ECB',
            32 => 'AES-256-ECB',
            default => 'AES-128-ECB',
        };
        if(empty($iv)){
            $encryptedData = openssl_encrypt($data, $algo, $key);
        }else{
            $encryptedData = openssl_encrypt($data, $algo, $key, 0, $iv);
        }

        return base64_encode($encryptedData);
    }

    function aesEcbDecrypt($encryptedData, $key, $iv = '') {
        $algo = match (strlen($key)) {
            24 => 'AES-192-ECB',
            32 => 'AES-256-ECB',
            default => 'AES-128-ECB',
        };
        $encryptedData = base64_decode($encryptedData);
        if(empty($iv)){
            $decryptedData = openssl_decrypt($encryptedData, $algo, $key);
        }else{
            $decryptedData = openssl_decrypt($encryptedData, $algo, $key, 0, $iv);
        }
        return $decryptedData;
    }

}